/*
 * shared.c
 *
 *  Created on: 2012-01-05
 *      Author: mateusz
 */

#include "shared.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/sem.h>
#include <sys/shm.h>
#include <unistd.h>

int getQueue(int id, int flags, int reset) {
	int msgid = msgget(id, flags);
	if (reset == 1) {
		msgctl(msgid, IPC_RMID, NULL);
		msgid = msgget(id, flags);
	}
	return msgid;
}

int sendIntMsg(int qID, long type, int msg) {
	intMsg.type = type;
	intMsg.mtext = msg;
	return msgsnd(qID, &intMsg, sizeof(intMsg) - sizeof(long), 0);
}

int getIntMsg(int qID, long type) {
	msgrcv(qID, &intMsg, sizeof(intMsg) - sizeof(long), type, 0);
	return intMsg.mtext;
}


int sendEntitiesMsg(int qID, long type) {
	entitiesMsg.type = type;
	return msgsnd(qID, &entitiesMsg, sizeof(entitiesMsg) - sizeof(long), 0);
}

int getEntitiesMsg(int qID, long type) {
	return msgrcv(qID, &entitiesMsg, sizeof(entitiesMsg), type, 0);
}

int sendLogMsg(int qID, long type) {
	logMsg.type = type;
	return msgsnd(qID, &logMsg, sizeof(logMsg) - sizeof(long), 0);
}

int getLogMsg(int qID, long type) {
	return msgrcv(qID, &logMsg, sizeof(logMsg) - sizeof(long), type, 0);
}

int sendCommandMsg(int qID, long type){
	commandMsg.type = type;
	return msgsnd(qID, &commandMsg, sizeof(commandMsg)-sizeof(long), 0);
}

int getCommandMsg(int qID, long type){
	return msgrcv(qID, &commandMsg, sizeof(commandMsg)-sizeof(long), type, 0);
}

// SEMAPHORES

void semOperation(int semid, int val) {
	sem.sem_num = 0;
	sem.sem_op = val;
	sem.sem_flg = 0;
	semop(semid, &sem, 1);
}

void semDown(int semid) {
	semOperation(semid, -1);
}

void semUp(int semid) {
	semOperation(semid, 1);
}

int semValue(int semid) {
	return semctl(semid, 0, GETVAL, 0);
}

int newSem(int id, int value) {
	int sem;
	sem = semget(id, 1, IPC_CREAT | 0600);
	semctl(sem, 0, SETVAL, value);
	return sem;
}

int getSem(int id){
	return semget(id, 1, 0600);
}

int newShm(int id, int size) {
	int shm;
	// if shm existed
	if ((shm = shmget(id, size, IPC_CREAT | 0600 | IPC_EXCL)) == -1) {
		shm = shmget(id, size, IPC_CREAT | 0600);
		shmctl(shm, IPC_RMID, NULL);
		shm = shmget(id, size, IPC_CREAT | 0600 | IPC_EXCL);
	}
	return shm;
}

int getShm(int id, int size){
	return shmget(id, size, 0600);
}
